/*
 * @Date         : 2024-05-14 09:47:41 星期2
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"

export function loggingClientInterceptor(options, nextCall) {
  const listener = new grpc.ListenerBuilder()
    .withOnReceiveMessage((message, next) => {
      logger(
        `(client):\t[${new Date().toISOString()}] Receive a message ${JSON.stringify(
          message
        )}`
      )
      next(message)
    })
    .build()

  const requester = new grpc.RequesterBuilder()
    .withSendMessage((message, next) => {
      logger(
        `(client):\t[${new Date().toISOString()}] Send a message ${JSON.stringify(
          message
        )}`
      )
      next(message)
    })
    .build()

  return new grpc.InterceptingCall(nextCall(options), requester)
}

export function loggingServerInterceptor(methodDescriptor, call) {
  const listener = new grpc.ServerListenerBuilder()
    .withOnReceiveMessage((message, next) => {
      logger(
        `(server):\t[${new Date().toISOString()}] Receive a message ${JSON.stringify(
          message
        )}`
      )
      next(message)
    })
    .build()

  const responder = new grpc.ResponderBuilder()
    .withStart((next) => next(listener))
    .withSendMessage((message, next) => {
      logger(
        `(server):\t[${new Date().toISOString()}] Send a message ${JSON.stringify(
          message
        )}`
      )
      next(message)
    })
    .build()

  return new grpc.ServerInterceptingCall(call, responder)
}

// 实际业务中可使用特定的日志库实现
function logger(format, ...args) {
  console.log(`LOG ${format}\n`, ...args)
}
